;
(function() {
  var Edit = window.wangEditor
  var editor = new Edit('#editor')
  editor.customConfig.zIndex = 100
  editor.customConfig.uploadImgServer = uploadUrl
  editor.customConfig.uploadFileName = 'file'
  editor.customConfig.customAlert = function(info) {}
  editor.customConfig.uploadImgHooks = {
    // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
    // （但是，服务器端返回的必须是一个 JSON 格式字符串！！！否则会报错）
    customInsert: function(insertImg, result, editor) {
      // 图片上传并返回结果，自定义插入图片的事件（而不是编辑器自动插入图片！！！）
      // insertImg 是插入图片的函数，editor 是编辑器对象，result 是服务器端返回的结果
      // 举例：假如上传图片成功后，服务器端返回的是 {url:'....'} 这种格式，即可这样插入图片：
      var url = result.url
      insertImg(url)
    }
  }

  // editor.txt.html()  读取内容
  // editor.txt.html('<p>用 JS 设置的内容</p>')   设置内容

  new Vue({
    el: '#notice-create',
    data: {
      flag: false,
      isImage: ['.jpg', '.jpeg', '.gif', '.png', '.bmp'],
      id: hlUrlUtil.GetQueryString('id'),
      files: [],
      stateList: [],
      modulesList: [],
      typelist: [],
      moduleId: '',
      articleTitle: '', //作者
      noticeTitle: '', //文章标题
      abstract: '',
      listImg: '',
      memo: '',
      status: '',
      // 2019-1-29 begin
      participateLt: [{
        name: '是',
        code: 'Y'
      }, {
        name: '否',
        code: 'N'
      }],
      participateAt: 'Y',
      dateTime: {
        begin: '',
        end: '',
        isDefalut: false
      },
      buttonName: '',
      moduleLt: [],
      fieldLt: [],
      isValidateLt: [{
        name: '是',
        code: true
      }, {
        name: '否',
        code: false
      }],
      moudleIndex: null,
      // 2019-1-29 end


      permissions: JSON.parse(window.localStorage.getItem('permissions')),
      isBindalert: false,
      alluser: [],
      isToTop: false, //是否置顶
      userList: [], //选中对象
      userListQs: [],
      dataList: [],
      progress: '',
    },
    methods: {
      //确认 (绑定钉钉用户到客户)
      surebind() {
        var arr = []
        this.alluser.forEach(item => {
          arr.push(item.id)
        })
        var that = this
        hlhttp.put({
          url: 'customer/bind_dd_users',
          data: {
            customer_id: that.selectedcustomer,
            corp_service_id: SERVERId,
            user_ids: arr.length ? arr.join(',') : '#'
          },
          success: function(data) {
            that.isBindalert = false
            that.getdd_users(that.selectedcustomer)
          }
        })
      },
      // 2019-1-29 begin
      participateSel(item) {
        this.participateAt = item.dictCode
      },

      fieldConfig() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'CSTM_JWK',
            config_name: 'CSTM_JWK_ANNC_TYPE'
          },
          success: (data) => {
            this.typelist = data;
          }
        })
      },
      addMoudle() {
        let flag = false;
        this.moduleLt.map(item => {
          if (!item.name) {
            flag = true;
          }
          if (!item.type) {
            flag = true;
          }
          if (!item.range) {
            flag = true;
          }
          if (item.flag0) {
            flag = true;
          }
          if (item.flag1) {
            flag = true;
          }
        })
        if (flag) {
          hl.toast('请先保存当前信息')
          return
        }
        this.moduleLt.push({
          name: '',
          oldName: '',
          type: '',
          type_name: '',
          range: '',
          oldRange: '',
          is_required: true,
          placeholder: '',
          flag0: true,
          flag1: true
        })
      },

      typeSel(item, i) {
        if (this.moduleLt[i].type != item.dictCode) {
          this.moduleLt[i].flag1 = true;
          this.moduleLt[i].range = '';
        }
        this.moduleLt[i].type = item.dictCode;
        this.moduleLt[i].type_name = item.dictName;
        if (this.moduleLt[i].type) {
          if (this.moduleLt[i].type == 'text' || this.moduleLt[i].type == 'textarea') {
            this.moduleLt[i].placeholder = '请填写数字'
          }
          if (this.moduleLt[i].type == 'radio' || this.moduleLt[i].type == 'checkbox') {
            this.moduleLt[i].placeholder = '请用英文逗号分隔'
          }
        }
      },

      // 2019-1-29 end

      //文件上传click()触发
      fileUp() {
        if (this.progress) {
          hl.toast('文件尚未上传完成')
          return
        }
        $('.fileButton').trigger('click')
      },
      fileToClick() {
        var that = this
        fileUpload('.fileButton', uploadUrl, (data) => {
          let type = data.json.name.substr(data.json.name.lastIndexOf('.'))
          if (this.isImage.indexOf(type) > -1) {
            this.files.push({
              name: data.json.name,
              url: data.json.url,
              type: 'pic'
            })
          }
          if (this.isImage.indexOf(type) == -1) {
            this.files.push({
              name: data.json.name,
              url: data.json.url,
              type: 'file'
            })
          }
        }, function(val) {
          that.progress = parseInt((val.loaded / val.total) * 100) + '%'
        })
      },
      //图片上传click()触发
      picUp() {
        $('.picButton').trigger('click')
      },
      picToClick() {
        imgupload('.picButton', uploadUrl, (data) => {
          this.listImg = data.json.url
        })
      },


      //获取状态
      eventStatus(code) {
        this.status = code
      },
      //删除指定附件
      delFile(index) {
        this.files.splice(index, 1)
      },
      //验证
      validateInfo() {
        if (!this.participateAt) {
          hl.toast('请选择类别')
          return false
        }
        if (!this.articleTitle) {
          hl.toast('请填写标题')
          return false
        }

        return true
      },
      //获取公告列表
      getListData() {
        hlhttp.get({
          url: 'portal/search_notice_list',
          data: {
            "keyword": '#',
            "notice_type": '#',
            "creator_name": '#',
            "orders": 'DESC',
            "columns": 'CT',
            "page": '1',
            "limit": '10000000'
          },
          success: (data) => {
            this.dataList = data.noticeList
          }
        })
      },
      //保存
      saveSubmit() {
        if (!this.validateInfo()) {
          return
        };
        if (this.isToTop) {
          var that = this
          for (let n = 0; n < that.dataList.length; n++) {
            if (that.dataList[n].noticeType == that.participateAt && that.dataList[n].stickyFlag == 'Y' && that.dataList[n].noticeId != that.id) {
              hllayer.confirm1('当前已存在置顶公告，继续置顶将取消已置顶的公告', function() {
                that.saveInfo()
              })
              return
            }
          }
          that.saveInfo();
        } else {
          this.saveInfo();
        }
      },
      // 保存信息调用方法
      saveInfo() {
        let url = [],
          name = [];
        this.files.map(item => {
          url.push(item.url)
          name.push(item.name)
        })
        let longTerm = '#';
        if (this.participateAt == 'Y') {
          longTerm = this.dateTime.isDefalut ? 'Y' : 'N'
        }
        let positionIds = [],
          positionNames = []
        this.userList.map(item => {
          positionIds.push(item.id)
          positionNames.push(item.name)
        })
        hlhttp.post({
          url: 'portal/notice',
          data: {
            notice_id: this.id,
            notice_type: this.participateAt,
            title: this.noticeTitle,
            author: this.articleTitle || '#',
            content: editor.txt.html(),
            attachments_url: url.toString() || '#',
            attachments_name: name.toString() || '#',
            sticky_flag: this.isToTop ? 'Y' : 'N',
            //new add
            position_ids: positionIds.toString(),
            position_names: positionNames.toString()
          },
          success: (data) => {
            hlUrlUtil.goTo('notice', {
              ddtab: true,
            }, false)
          }
        })
      },


      //预览
      previewInfo() {
        if (!this.validateInfo()) {
          return
        };
        hlUrlUtil.goTo('noticePrevew', {
					id: this.id,
          ddtab: true,
        }, true)
      },
      //组织筛选项
      selectOrg() {
        this.isBindalert = true
        setTimeout(() => {
          approve.data.getCount = false
          approve.data.memberType = 'A';
          approve.data.ddflag = true
          approve.dom.addinitialDom()
          approve.methods.ddwxTab();
          approve.event.wxddNodeEvent((data) => {
            this.userList = data
          })
        }, 30)
      },
      // 减少客户（弹出框右侧）
      reduceCus(index) {
        this.userList.splice(index, 1)
        approve.data.selectPerson = this.userList
        approve.dom.showRight()
      },
      surebind() {
        this.isBindalert = false
      },
      //获取详情
      detailDt() {
        hlhttp.get({
          url: 'portal/park_notice',
          data: {
            id: this.id
          },
          success: (data) => {
            this.$refs.type.innerHTML = data.noticeTypeVal;
            this.participateAt = data.noticeType;
            this.noticeTitle = data.title;
            this.isToTop = data.stickyFlag == 'Y' ? true : false;
            this.articleTitle = data.author;
            editor.txt.html(data.content)
            if (data.attachmentsName) {
              data.attachmentsName.split(',').map((item, index) => {
                let type = item.substr(item.lastIndexOf('.'))
                if (this.isImage.indexOf(type) > -1) {
                  this.files.push({
                    name: item,
                    url: data.attachmentsUrl.split(',')[index],
                    type: 'pic'
                  })
                }
                if (this.isImage.indexOf(type) == -1) {
                  this.files.push({
                    name: item,
                    url: data.attachmentsUrl.split(',')[index],
                    type: 'file'
                  })
                }
              })
            }
            if (data.positionIds) {
              data.positionNames.split(',').map((item, index) => {
                this.userList.push({
                  id: data.positionIds.split(',')[index],
                  name: item
                })
              })
              approve.data.selectPerson = this.userList
              approve.dom.showRight()
            }
          }
        })
      }
    },
    created() {
      hlSelectUi()
    },
    mounted() {
      editor.create()
      this.fileToClick()
      this.picToClick()
      this.fieldConfig()
      this.detailDt()
      this.getListData()
      approve.dom.addinitialDom()
      approve.event.wxddNodeEvent((data) => {
        this.userList = data;
      })
    }
  })
}())
